





<!DOCTYPE html>
<html class="writer-html5" lang="zh-CN" >
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>使用TVM部署预先量化的框架模型-第3部分（TFLite） &mdash; tvm 0.8.dev1982 文档</title>
  

  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/tlcpack_theme.css" type="text/css" />

  
  
    <link rel="shortcut icon" href="../../_static/tvm-logo-square.png"/>
  

  
  
  
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
        <script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
        <script src="../../_static/jquery.js"></script>
        <script src="../../_static/underscore.js"></script>
        <script src="../../_static/doctools.js"></script>
        <script src="../../_static/translations.js"></script>
    
    <script type="text/javascript" src="../../_static/js/theme.js"></script>

    
    <script type="text/javascript" src="../../_static/js/tlcpack_theme.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="在Cuda上部署一个量化模型" href="deploy_quantized.html" />
    <link rel="prev" title="使用TVM部署一个框架预量化模型" href="deploy_prequantized.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    
<header class="header">
    <div class="innercontainer">
      <div class="headerInner d-flex justify-content-between align-items-center">
          <div class="headerLogo">
               <a href="https://tvm.apache.org/"><img src=https://tvm.apache.org/assets/images/logo.svg alt="logo"></a>
          </div>

          <div id="headMenu" class="headerNav">
            <button type="button" id="closeHeadMenu" class="navCloseBtn"><img src="../../_static/img/close-icon.svg" alt="Close"></button>
             <ul class="nav">
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/community>Community</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/download>Download</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/vta>VTA</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/blog>Blog</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/docs>Docs</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmconf.org>Conference</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://github.com/apache/tvm/>Github</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmchinese.github.io/declaration_zh_CN.html>About-Translators</a>
                </li>
             </ul>
               <div class="responsivetlcdropdown">
                 <button type="button" class="btn-link">
                   ASF
                 </button>
                 <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                 </ul>
               </div>
          </div>
            <div class="responsiveMenuIcon">
              <button type="button" id="menuBtn" class="btn-menu"><img src="../../_static/img/menu-icon.svg" alt="Menu Icon"></button>
            </div>

            <div class="tlcDropdown">
              <div class="dropdown">
                <button type="button" class="btn-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  ASF
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                  </ul>
                </div>
              </div>
          </div>
       </div>
    </div>
 </header>
 
    <nav data-toggle="wy-nav-shift" class="wy-nav-side fixed">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../index.html">
          

          
            
            <img src="../../_static/tvm-logo-small.png" class="logo" alt="Logo"/>
          
          </a>

          
            
            
                <div class="version">
                  0.8.dev1982
                </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption" role="heading"><span class="caption-text">如何开始</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../install/index.html">安装 TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../contribute/index.html">贡献者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">用户引导</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../tutorial/index.html">User Tutorial</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index.html">How To Guides</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../compile_models/index.html">编译深度学习模型</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="../deploy/index.html">TVM 部署模型和集成</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#build-the-tvm-runtime-library">构建 TVM 运行 runtime 库</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#cross-compile-the-tvm-runtime-for-other-architectures">为其它架构交叉编译TVM runtime</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#optimize-and-tune-models-for-target-devices">针对目标设备优化和调整模型</a></li>
<li class="toctree-l3"><a class="reference internal" href="../deploy/index.html#deploy-optimized-model-on-target-devices">在目标设备上部署优化的模型</a></li>
<li class="toctree-l3 current"><a class="reference internal" href="../deploy/index.html#additional-deployment-how-tos">其他部署方式</a><ul class="current">
<li class="toctree-l4 current"><a class="reference internal" href="index.html">Deploy Deep Learning Models</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_relay/index.html">Work With Relay</a></li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_schedules/index.html">Work With Tensor Expression and Schedules</a></li>
<li class="toctree-l2"><a class="reference internal" href="../optimize_operators/index.html">优化张量算子</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autotvm/index.html">Auto-Tune with Templates and AutoTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autoscheduler/index.html">Use AutoScheduler for Template-Free Scheduling</a></li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_microtvm/index.html">Work With microTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extend_tvm/index.html">Extend TVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../profile/index.html">Profile Models</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../errors.html">Handle TVM Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../faq.html">常见提问</a></li>
</ul>
</li>
</ul>
<p class="caption" role="heading"><span class="caption-text">开发者引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../dev/tutorial/index.html">Developer Tutorial</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../dev/how_to/how_to.html">开发者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">架构指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../arch/index.html">Design and Architecture</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">主题引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../topic/microtvm/index.html">microTVM：裸机使用TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../topic/vta/index.html">VTA: Versatile Tensor Accelerator</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">参考指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../reference/langref/index.html">语言参考</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/python/index.html">Python API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/links.html">Other APIs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../genindex.html">索引</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
      
      <nav class="wy-nav-top" aria-label="top navigation" data-toggle="wy-nav-top">
        
            <div class="togglemenu">

            </div>
            <div class="nav-content">
              <!-- tvm -->
              Table of content
            </div>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        

          




















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../index.html">Docs</a> <span class="br-arrow">></span></li>
        
          <li><a href="../index.html">How To Guides</a> <span class="br-arrow">></span></li>
        
          <li><a href="../deploy/index.html">TVM 部署模型和集成</a> <span class="br-arrow">></span></li>
        
          <li><a href="index.html">Deploy Deep Learning Models</a> <span class="br-arrow">></span></li>
        
      <li>使用TVM部署预先量化的框架模型-第3部分（TFLite）</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../../_sources/how_to/deploy_models/deploy_prequantized_tflite.rst.txt" rel="nofollow"> <img src="../../_static//img/source.svg" alt="viewsource"/></a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="sphx-glr-download-link-note admonition note">
<p class="admonition-title">注解</p>
<p>点击 <a class="reference internal" href="#sphx-glr-download-how-to-deploy-models-deploy-prequantized-tflite-py"><span class="std std-ref">这里</span></a> 下载完整的样例代码</p>
</div>
<div class="sphx-glr-example-title section" id="deploy-a-framework-prequantized-model-with-tvm-part-3-tflite">
<span id="sphx-glr-how-to-deploy-models-deploy-prequantized-tflite-py"></span><h1>使用TVM部署预先量化的框架模型-第3部分（TFLite）<a class="headerlink" href="#deploy-a-framework-prequantized-model-with-tvm-part-3-tflite" title="永久链接至标题">¶</a></h1>
<p><strong>作者</strong>: <a class="reference external" href="https://github.com/siju-samuel">Siju Samuel</a></p>
<p>欢迎来到使用TVM部署预先量化的框架模型教程的第3部分。在这一部分中，我们将从一个量化的TFLite图开始，然后通过TVM编译并执行它。</p>
<p>有关使用TFLite量化模型的更多详细信息，请读者阅读`转换量化模型 &lt;<a class="reference external" href="https://www.tensorflow.org/lite/convert/quantization">https://www.tensorflow.org/lite/convert/quantization</a>&gt;`_.</p>
<p>可以从此链接下载TFLite模型`link &lt;<a class="reference external" href="https://www.tensorflow.org/lite/guide/hosted_models">https://www.tensorflow.org/lite/guide/hosted_models</a>&gt;`_.</p>
<p>首先，需要先安装Tensorflow和TFLite软件包。</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="c1"># install tensorflow and tflite</span>
pip install <span class="nv">tensorflow</span><span class="o">==</span><span class="m">2</span>.1.0
pip install <span class="nv">tflite</span><span class="o">==</span><span class="m">2</span>.1.0
</pre></div>
</div>
<p>现在请检查 TFLite 包是否安装成功，<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">&quot;import</span> <span class="pre">tflite&quot;</span></code></p>
<div class="section" id="necessary-imports">
<h2>必要导入<a class="headerlink" href="#necessary-imports" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">tflite</span>

<span class="kn">import</span> <span class="nn">tvm</span>
<span class="kn">from</span> <span class="nn">tvm</span> <span class="k">import</span> <span class="n">relay</span>
</pre></div>
</div>
</div>
<div class="section" id="download-pretrained-quantized-tflite-model">
<h2>下载预训练量化TFLite模型<a class="headerlink" href="#download-pretrained-quantized-tflite-model" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Download mobilenet V2 TFLite model provided by Google</span>
<span class="kn">from</span> <span class="nn">tvm.contrib.download</span> <span class="k">import</span> <span class="n">download_testdata</span>

<span class="n">model_url</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s2">&quot;https://storage.googleapis.com/download.tensorflow.org/models/&quot;</span>
    <span class="s2">&quot;tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz&quot;</span>
<span class="p">)</span>

<span class="c1"># Download model tar file and extract it to get mobilenet_v2_1.0_224.tflite</span>
<span class="n">model_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span>
    <span class="n">model_url</span><span class="p">,</span> <span class="s2">&quot;mobilenet_v2_1.0_224_quant.tgz&quot;</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;tf&quot;</span><span class="p">,</span> <span class="s2">&quot;official&quot;</span><span class="p">]</span>
<span class="p">)</span>
<span class="n">model_dir</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">model_path</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="utils-for-downloading-and-extracting-zip-files">
<h2>用于下载和解压 zip 文件的工具<a class="headerlink" href="#utils-for-downloading-and-extracting-zip-files" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">extract</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
    <span class="kn">import</span> <span class="nn">tarfile</span>

    <span class="k">if</span> <span class="n">path</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s2">&quot;tgz&quot;</span><span class="p">)</span> <span class="ow">or</span> <span class="n">path</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s2">&quot;gz&quot;</span><span class="p">):</span>
        <span class="n">dir_path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
        <span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
        <span class="n">tar</span><span class="o">.</span><span class="n">extractall</span><span class="p">(</span><span class="n">path</span><span class="o">=</span><span class="n">dir_path</span><span class="p">)</span>
        <span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;Could not decompress the file: &quot;</span> <span class="o">+</span> <span class="n">path</span><span class="p">)</span>


<span class="n">extract</span><span class="p">(</span><span class="n">model_path</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="load-a-test-image">
<h2>加载一张测试图片<a class="headerlink" href="#load-a-test-image" title="永久链接至标题">¶</a></h2>
</div>
<div class="section" id="get-a-real-image-for-e2e-testing">
<h2>获取e2e测试的真实图像<a class="headerlink" href="#get-a-real-image-for-e2e-testing" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_real_image</span><span class="p">(</span><span class="n">im_height</span><span class="p">,</span> <span class="n">im_width</span><span class="p">):</span>
    <span class="kn">from</span> <span class="nn">PIL</span> <span class="k">import</span> <span class="n">Image</span>

    <span class="n">repo_base</span> <span class="o">=</span> <span class="s2">&quot;https://github.com/dmlc/web-data/raw/main/tensorflow/models/InceptionV1/&quot;</span>
    <span class="n">img_name</span> <span class="o">=</span> <span class="s2">&quot;elephant-299.jpg&quot;</span>
    <span class="n">image_url</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">repo_base</span><span class="p">,</span> <span class="n">img_name</span><span class="p">)</span>
    <span class="n">img_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span><span class="n">image_url</span><span class="p">,</span> <span class="n">img_name</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="s2">&quot;data&quot;</span><span class="p">)</span>
    <span class="n">image</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">img_path</span><span class="p">)</span><span class="o">.</span><span class="n">resize</span><span class="p">((</span><span class="n">im_height</span><span class="p">,</span> <span class="n">im_width</span><span class="p">))</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">image</span><span class="p">)</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="s2">&quot;uint8&quot;</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">im_height</span><span class="p">,</span> <span class="n">im_width</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">data</span>


<span class="n">data</span> <span class="o">=</span> <span class="n">get_real_image</span><span class="p">(</span><span class="mi">224</span><span class="p">,</span> <span class="mi">224</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="load-a-tflite-model">
<h2>加载tflite模型<a class="headerlink" href="#load-a-tflite-model" title="永久链接至标题">¶</a></h2>
<p>现在我们可以打开mobilenet_v2_1.0_224.tflite</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tflite_model_file</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">model_dir</span><span class="p">,</span> <span class="s2">&quot;mobilenet_v2_1.0_224_quant.tflite&quot;</span><span class="p">)</span>
<span class="n">tflite_model_buf</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">tflite_model_file</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="c1"># Get TFLite model from buffer</span>
<span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">tflite</span>

    <span class="n">tflite_model</span> <span class="o">=</span> <span class="n">tflite</span><span class="o">.</span><span class="n">Model</span><span class="o">.</span><span class="n">GetRootAsModel</span><span class="p">(</span><span class="n">tflite_model_buf</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">tflite.Model</span>

    <span class="n">tflite_model</span> <span class="o">=</span> <span class="n">tflite</span><span class="o">.</span><span class="n">Model</span><span class="o">.</span><span class="n">Model</span><span class="o">.</span><span class="n">GetRootAsModel</span><span class="p">(</span><span class="n">tflite_model_buf</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>让我们运行TFLite预量化模型推断并获得TFLite预测。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">run_tflite_model</span><span class="p">(</span><span class="n">tflite_model_buf</span><span class="p">,</span> <span class="n">input_data</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Generic function to execute TFLite&quot;&quot;&quot;</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="kn">from</span> <span class="nn">tensorflow</span> <span class="k">import</span> <span class="n">lite</span> <span class="k">as</span> <span class="n">interpreter_wrapper</span>
    <span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
        <span class="kn">from</span> <span class="nn">tensorflow.contrib</span> <span class="k">import</span> <span class="n">lite</span> <span class="k">as</span> <span class="n">interpreter_wrapper</span>

    <span class="n">input_data</span> <span class="o">=</span> <span class="n">input_data</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">input_data</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span> <span class="k">else</span> <span class="p">[</span><span class="n">input_data</span><span class="p">]</span>

    <span class="n">interpreter</span> <span class="o">=</span> <span class="n">interpreter_wrapper</span><span class="o">.</span><span class="n">Interpreter</span><span class="p">(</span><span class="n">model_content</span><span class="o">=</span><span class="n">tflite_model_buf</span><span class="p">)</span>
    <span class="n">interpreter</span><span class="o">.</span><span class="n">allocate_tensors</span><span class="p">()</span>

    <span class="n">input_details</span> <span class="o">=</span> <span class="n">interpreter</span><span class="o">.</span><span class="n">get_input_details</span><span class="p">()</span>
    <span class="n">output_details</span> <span class="o">=</span> <span class="n">interpreter</span><span class="o">.</span><span class="n">get_output_details</span><span class="p">()</span>

    <span class="c1"># set input</span>
    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_data</span><span class="p">)</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">input_details</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">input_details</span><span class="p">)):</span>
        <span class="n">interpreter</span><span class="o">.</span><span class="n">set_tensor</span><span class="p">(</span><span class="n">input_details</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="s2">&quot;index&quot;</span><span class="p">],</span> <span class="n">input_data</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>

    <span class="c1"># Run</span>
    <span class="n">interpreter</span><span class="o">.</span><span class="n">invoke</span><span class="p">()</span>

    <span class="c1"># get output</span>
    <span class="n">tflite_output</span> <span class="o">=</span> <span class="nb">list</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">output_details</span><span class="p">)):</span>
        <span class="n">tflite_output</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">interpreter</span><span class="o">.</span><span class="n">get_tensor</span><span class="p">(</span><span class="n">output_details</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="s2">&quot;index&quot;</span><span class="p">]))</span>

    <span class="k">return</span> <span class="n">tflite_output</span>
</pre></div>
</div>
<p>让我们运行TVM编译的预量化模型推断并获得TVM预测。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">run_tvm</span><span class="p">(</span><span class="n">lib</span><span class="p">):</span>
    <span class="kn">from</span> <span class="nn">tvm.contrib</span> <span class="k">import</span> <span class="n">graph_executor</span>

    <span class="n">rt_mod</span> <span class="o">=</span> <span class="n">graph_executor</span><span class="o">.</span><span class="n">GraphModule</span><span class="p">(</span><span class="n">lib</span><span class="p">[</span><span class="s2">&quot;default&quot;</span><span class="p">](</span><span class="n">tvm</span><span class="o">.</span><span class="n">cpu</span><span class="p">(</span><span class="mi">0</span><span class="p">)))</span>
    <span class="n">rt_mod</span><span class="o">.</span><span class="n">set_input</span><span class="p">(</span><span class="s2">&quot;input&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
    <span class="n">rt_mod</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
    <span class="n">tvm_res</span> <span class="o">=</span> <span class="n">rt_mod</span><span class="o">.</span><span class="n">get_output</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
    <span class="n">tvm_pred</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">squeeze</span><span class="p">(</span><span class="n">tvm_res</span><span class="p">)</span><span class="o">.</span><span class="n">argsort</span><span class="p">()[</span><span class="o">-</span><span class="mi">5</span><span class="p">:][::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">tvm_pred</span><span class="p">,</span> <span class="n">rt_mod</span>
</pre></div>
</div>
</div>
<div class="section" id="tflite-inference">
<h2>TFLite推理<a class="headerlink" href="#tflite-inference" title="永久链接至标题">¶</a></h2>
<p>在量化模型上运行TFLite推理。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tflite_res</span> <span class="o">=</span> <span class="n">run_tflite_model</span><span class="p">(</span><span class="n">tflite_model_buf</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
<span class="n">tflite_pred</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">squeeze</span><span class="p">(</span><span class="n">tflite_res</span><span class="p">)</span><span class="o">.</span><span class="n">argsort</span><span class="p">()[</span><span class="o">-</span><span class="mi">5</span><span class="p">:][::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="tvm-compilation-and-inference">
<h2>TVM编译与推理<a class="headerlink" href="#tvm-compilation-and-inference" title="永久链接至标题">¶</a></h2>
<p>我们使用TFLite-Relay解析器将TFLite预量化图转换为Relay IR。注意，预量化模型的前端解析器调用与FP32模型的前端解析器调用完全相同。我们鼓励您从print(mod)中删除注释，并检查Relay模块。您将会看到很多QNN算子，比如Requantize, Quantize和QNN Conv2D。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">dtype_dict</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;input&quot;</span><span class="p">:</span> <span class="n">data</span><span class="o">.</span><span class="n">dtype</span><span class="o">.</span><span class="n">name</span><span class="p">}</span>
<span class="n">shape_dict</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;input&quot;</span><span class="p">:</span> <span class="n">data</span><span class="o">.</span><span class="n">shape</span><span class="p">}</span>

<span class="n">mod</span><span class="p">,</span> <span class="n">params</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">frontend</span><span class="o">.</span><span class="n">from_tflite</span><span class="p">(</span><span class="n">tflite_model</span><span class="p">,</span> <span class="n">shape_dict</span><span class="o">=</span><span class="n">shape_dict</span><span class="p">,</span> <span class="n">dtype_dict</span><span class="o">=</span><span class="n">dtype_dict</span><span class="p">)</span>
<span class="c1"># print(mod)</span>
</pre></div>
</div>
<p>现在让我们编译Relay模块。我们在这里使用 “llvm” 为目标。您可以将其替换为您感兴趣的目标平台。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">target</span> <span class="o">=</span> <span class="s2">&quot;llvm&quot;</span>
<span class="k">with</span> <span class="n">tvm</span><span class="o">.</span><span class="n">transform</span><span class="o">.</span><span class="n">PassContext</span><span class="p">(</span><span class="n">opt_level</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="n">lib</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">build_module</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="n">mod</span><span class="p">,</span> <span class="n">target</span><span class="o">=</span><span class="n">target</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="n">params</span><span class="p">)</span>
</pre></div>
</div>
<p>最后，让我们在TVM编译模块上调用推理。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tvm_pred</span><span class="p">,</span> <span class="n">rt_mod</span> <span class="o">=</span> <span class="n">run_tvm</span><span class="p">(</span><span class="n">lib</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="accuracy-comparison">
<h2>精度比较<a class="headerlink" href="#accuracy-comparison" title="永久链接至标题">¶</a></h2>
<p>打印MXNet和TVM推断的前5个标签。检查标签，因为TFLite和Relay之间的requantize实现是不同的。这将导致最终输出数字不匹配。因此，通过标签测试准确性。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">&quot;TVM Top-5 labels:&quot;</span><span class="p">,</span> <span class="n">tvm_pred</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;TFLite Top-5 labels:&quot;</span><span class="p">,</span> <span class="n">tflite_pred</span><span class="p">)</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>TVM Top-5 labels: [387 102 386 349 341]
TFLite Top-5 labels: [387 102 386 341 880]
</pre></div>
</div>
</div>
<div class="section" id="measure-performance">
<h2>测试性能<a class="headerlink" href="#measure-performance" title="永久链接至标题">¶</a></h2>
<p>在这里我们举了一个例子来说明如何测试TVM编译模型的性能。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">n_repeat</span> <span class="o">=</span> <span class="mi">100</span>  <span class="c1"># should be bigger to make the measurement more accurate</span>
<span class="n">dev</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">cpu</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">rt_mod</span><span class="o">.</span><span class="n">benchmark</span><span class="p">(</span><span class="n">dev</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">repeat</span><span class="o">=</span><span class="n">n_repeat</span><span class="p">))</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Execution time summary:
 mean (ms)   median (ms)    max (ms)     min (ms)     std (ms)
  94.9588      93.4645      114.0041     90.7779       3.7725
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>除非硬件对快速8位指令有特殊支持，否则量化模型不会比FP32模型更快。没有快速的8位指令，TVM用16位进行量化卷积，即使模型本身是8位的。</p>
<p>对于x86，可以在设置AVX512指令的cpu上实现最佳性能。在这种情况下，TVM为给定的目标使用最快的8位指令。这包括对VNNI 8位点积指令(CascadeLake或更新版本)的支持。对于EC2 C5.12x大实例，本教程的TVM延迟约为2毫秒。</p>
<p>对于许多TFLite网络，ARM上的Intel con2d NCHWc调度比ARM NCHW con2d空间包调度提供更好的端到端延迟。ARM winograd的性能更高，但它有一个高内存占用。</p>
<p>此外，以下关于CPU 性能的提示同样适用：</p>
<blockquote>
<div><ul class="simple">
<li><p>将环境变量TVM_NUM_THREADS设置为物理核的数量</p></li>
<li><p>为你的硬件选择最好的目标，比如“llvm -mcpu=skylake-avx512”或“llvm -mcpu=cascadelake”(将来会有更多带有AVX512的cpu)</p></li>
<li><p>执行自动调优-‘为x86 CPU自动调优卷积网络&lt;<a class="reference external" href="https://tvm.apache.org/docs/tutorials/autotvm/tune_relay_x86.html">https://tvm.apache.org/docs/tutorials/autotvm/tune_relay_x86.html</a>&gt;`_.</p></li>
<li><p>为了在ARM CPU上获得最佳的推断性能，根据您的设备改变目标参数，并遵循`自动调优ARM CPU的卷积网络&lt;<a class="reference external" href="https://tvm.apache.org/docs/tutorials/autotvm/tune_relay_arm.html">https://tvm.apache.org/docs/tutorials/autotvm/tune_relay_arm.html</a>&gt;`_.</p></li>
</ul>
</div></blockquote>
</div>
<p class="sphx-glr-timing"><strong>脚本总运行时间:</strong> ( 2 minutes  7.334 seconds)</p>
<div class="sphx-glr-footer class sphx-glr-footer-example docutils container" id="sphx-glr-download-how-to-deploy-models-deploy-prequantized-tflite-py">
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/56691c7a27d45da61d112276334640d3/deploy_prequantized_tflite.py"><code class="xref download docutils literal notranslate"><span class="pre">下载Python源码:</span> <span class="pre">deploy_prequantized_tflite.py</span></code></a></p>
</div>
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/1a26d790f7b98309d730181290dae3ee/deploy_prequantized_tflite.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">下载Jupyter</span> <span class="pre">notebook:</span> <span class="pre">deploy_prequantized_tflite.ipynb</span></code></a></p>
</div>
</div>
<p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p>
</div>
</div>


           </div>
           
          </div>
          

<footer>

    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="deploy_quantized.html" class="btn btn-neutral float-right" title="在Cuda上部署一个量化模型" accesskey="n" rel="next">下一个 <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="deploy_prequantized.html" class="btn btn-neutral float-left" title="使用TVM部署一个框架预量化模型" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> 上一个</a>
      
    </div>

<div id="button" class="backtop"><img src="../../_static//img/right.svg" alt="backtop"/> </div>
<section class="footerSec">
    <div class="footerHeader">
      <ul class="d-flex align-md-items-center justify-content-between flex-column flex-md-row">
        <li class="copywrite d-flex align-items-center">
          <h5 id="copy-right-info">© 2020 Apache Software Foundation | All right reserved</h5>
        </li>
      </ul>

    </div>

    <ul>
      <li class="footernote">Copyright © 2020 The Apache Software Foundation. Apache TVM, Apache, the Apache feather, and the Apache TVM project logo are either trademarks or registered trademarks of the Apache Software Foundation.</li>
    </ul>

</section>
</footer>
        </div>
      </div>

    </section>

  </div>
  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

  </body>
  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
    <!-- Theme Analytics -->
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-75982049-2', 'auto');
    ga('send', 'pageview');
    </script>

    
   

</body>
</html>